package com.bifrost.task.support;

import com.bifrost.exception.FTPClientException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Author by yanxiaobo
 * Date on 2018/6/12$.
 */
public class FtpClientFactory implements PooledObjectFactory<FTPClient> {
    Logger logger = LoggerFactory.getLogger(FtpClientFactory.class);

    private  FTPClientConfigure config;


    @Override
    public PooledObject<FTPClient> makeObject() {
        FtpConnectWrapper ftpConnectWrapper = new FtpConnectWrapper(new FTPClient());
        FTPClient ftpClient = ftpConnectWrapper.getObject();
        try {
            ftpClient.connect(config.getHost(), config.getPort());
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                logger.warn("FTPServer refused connection");
                return null;
            }
            boolean result = ftpClient.login(config.getUsername(), config.getPassword());
            if (!result) {
                throw new FTPClientException("ftpClient登陆失败! userName:" + config.getUsername() + " ; password:" + config.getPassword());
            }
            ftpClient.setFileType(config.getTransferFileType());
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding(config.getEncoding());
            if (config.getPassiveMode().equals("true")) {
                ftpClient.enterLocalPassiveMode();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (FTPClientException e) {
            e.printStackTrace();
        }
        return ftpConnectWrapper;
    }


    @Override
    public void destroyObject(PooledObject<FTPClient> pooledObject){
        FTPClient ftpClient = pooledObject.getObject();
        try {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.logout();
            }
        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            // 注意,一定要在finally代码中断开连接，否则会导致占用ftp连接情况
            try {
                ftpClient.disconnect();
            } catch (IOException io) {
                io.printStackTrace();
            }
        }
    }

    @Override
    public boolean validateObject(PooledObject<FTPClient> pooledObject) {
        FTPClient ftpClient = pooledObject.getObject();
        try {
            return ftpClient.sendNoOp();
        } catch (IOException e) {
            logger.warn("Failed to validate client: " + e, e);
            return false;
        }
    }

    @Override
    public void activateObject(PooledObject<FTPClient> pooledObject) throws Exception {

    }

    @Override
    public void passivateObject(PooledObject<FTPClient> pooledObject) throws Exception {

    }

    public FTPClientConfigure getConfig() {
        return config;
    }

    public void setConfig(FTPClientConfigure config) {
        this.config = config;
    }
}
